<template>
  <view class="container">
    <view class="top-txt">
      {{ cates[questionList[shuffleIndex[index]].cate_id]?.content }}
    </view>

    <!-- view class='bg-pic' style="background:url({{imagePath}}/app4/bg2.jpg)" -->
    <view class="bg-pic">
      <image :src="imagePath + '/app4/bg2.jpg'" />
      <image v-if="showcatebg" class="cover" :src="imagePath + '/app4/catebg/' + cates[questionList[shuffleIndex[index]].cate_id]?.title + '.png'" />
    </view>

    <view class="faq">
      <view class="faq-num">
        {{ index + 1 }}/{{ num }}
      </view>

      <view class="line">
        <image :src="imagePath + '/app4/line.png'" />
      </view>

      <view class="tit">
        {{ questionList[shuffleIndex[index]].question }}
        {{ questionList[shuffleIndex[index]].type == 1 || questionList[shuffleIndex[index]].type == 3 ? '【单选】' : '【多选】' }}
      </view>
      <!-- （{{questionList[shuffleIndex[index]].scores}}分） -->
      <view class="line">
        <image :src="imagePath + '/app4/line.png'" />
      </view>

      <view class="faq-box">
        <radio-group v-if="questionList[shuffleIndex[index]].type == 1" class="radio-group" @change="radioChange">
          <label
            v-for="(value, key) in questionList[shuffleIndex[index]].option"
            :key="key"
            :style="questionList[shuffleIndex[index]].options_type == 2 ? 'display:inline-block' : ''"
            :data-index="key"
            :class="'item radio my-choosebox ' + (String(key) === String(activeItemIndex) ? 'active' : '') + ' ' + (questionList[shuffleIndex[index]].options_type == 2 ? 'hafe' : '')"
            @tap="changestyle"
          >
            <template v-if="questionList[shuffleIndex[index]].options_type == 2">
              <view class="view" style="line-height:100rpx;" @tap="changestyle">
                <radio :data-index="key" :value="key" :checked="questionList[shuffleIndex[index]].checked" @tap="changestyle" />
                {{ key }}、
                <image :data-index="key" style="object-fit: cover; width: 100%; height: 180rpx" :src="value.value" @tap="changestyle" />
              </view>
            </template>
            <template v-else>
              <radio :data-index="key" :value="key" :checked="questionList[shuffleIndex[index]].checked" @tap="changestyle" />
              {{ key }}、{{ value.value }}
            </template>
          </label>
        </radio-group>

        <checkbox-group v-else-if="questionList[shuffleIndex[index]].type == 2" @change="checkboxChange">
          <label
            v-for="(value, key) in questionList[shuffleIndex[index]].option"
            :key="key"
            :style="questionList[shuffleIndex[index]].options_type == 2 ? 'display:inline-block' : ''"
            :data-index="key"
            :class="'item checkbox my-choosebox    ' + (questionList[shuffleIndex[index]].options_type == 2 ? 'hafe' : '') + ' ' + (value.ischeck ? 'ischeck' : '')"
            @tap="changestyle"
          >
            <template v-if="questionList[shuffleIndex[index]].options_type == 2">
              <view class="view" style="line-height:100rpx;" @tap="changestyle">
                <checkbox :value="key" :checked="questionList[shuffleIndex[index]].checked" />
                {{ key }}、
                <image :data-index="key" style="object-fit: cover; width: 100%; height: 180rpx" :src="value.value" @tap="changestyle" />
              </view>
            </template>
            <template v-else>
              <checkbox :data-index="key" :value="key" :checked="questionList[shuffleIndex[index]].checked" @tap="changestyle" />
              {{ key }}、{{ value.value }}
            </template>
          </label>
        </checkbox-group>

        <radio-group v-else class="radio-group" @change="radioChange">
          <label
            v-for="(item, key) in questionList[shuffleIndex[index]].option"
            :key="key"
            :data-index="key"
            :class="'item radio my-choosebox ' + (String(key) === String(activeItemIndex) ? 'active' : '')"
            @tap="changestyle"
          >
            <radio :value="item" :checked="questionList[shuffleIndex[index]].checked" />

            {{ item }}
          </label>
        </radio-group>
      </view>
    </view>

    <view class="faq-btn">
      <template v-if="isanswer">
        <view class="btn-box">
          <template v-if="answer_true">
            <!-- <button class='btn'><image src="{{imagePath}}/app4/right.png"></image>回答正确</button> -->
            <button class="btn" @tap="nextSubmit">
              <image :src="imagePath + '/app4/right.png'" />
              {{ nexbutton_txt }}
            </button>
          </template>

          <template v-else>
            <button class="btn" @tap="requeren">
              <image :src="imagePath + '/app4/wrong.png'" />
              重新回答
            </button>
            <!-- <button class='btn' bindtap='nextSubmit'>下一题</button> -->
          </template>
        </view>
      </template>

      <template v-else>
        <button class="btn" hover-class="btn-hover" @tap="queren">
          确定
        </button>
      </template>

      <!--view wx:if="{{answer_true}}" class="text"><image style="width:20px;height:20px;" src="{{imagePath}}/app4/right.png"></image><text>回答正确</text></view>
			<view wx:else class="text"><image  style="width:20px;height:20px;" src="{{imagePath}}/app4/wrong.png"></image><text>回答错误</text></view-->

      <!-- button class='btn' bindtap='requeren' style="display:{{reanwser_box_display}}">重新回答</button -->
      <!-- button class='btn' hover-class="btn-hover" bindtap='nextSubmit' style="display:{{next_box_display}}">下一题</button -->

      <!-- <button bindtap='outTest' class="toindex-btn">退出答题</button> -->
    </view>

    <!-- 这里是弹出框，回答问题点确定之后弹出。 -->

    <view class="pop-box" :style="'display:' + pop_box_display">
      <text>正确答案为：{{ trueValue }}</text>
      <view class="faq-tips">
        {{ cates[questionList[shuffleIndex[index]].cate_id]?.content }}
      </view>

      <view style="color: #ffffff; font-size: 32rpx; position: absolute; right: 10rpx; bottom: 10rpx">
        {{ second }}
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import service from '../../service/service'
import { questionList as questionListApi, questionDetail } from '../../service/api'
// @ts-ignore
const app = getApp() as any
let setTimer: any = null

const imagePath = ref(app.globalData.imagePath)
const anwser_box_display = ref('block')
const reanwser_box_display = ref('none')
const next_box_display = ref('none')
const questionList = ref<any[]>([])
const nexbutton_txt = ref('下一题')
const height = ref(20)
const focus = ref(false)
const text = ref('点击文字输入框输入文字')
const list = ref<any[]>([])
const cates = ref<any[]>([])
const size = ref(20)
const page = ref(1)
const index = ref(0)
const num = ref(10)
const second = ref(10)
const chooseValue = ref<any[]>([])
const totalScore = ref(100)
const right = ref(0)
const wrong = ref(0)
const wrongList = ref<any[]>([])
const wrongListSort = ref<any[]>([])
const pop_box_display = ref('none')
const isjump = ref(false)
const shuffleIndex = ref<any[]>([])
const showcatebg = ref(false)
const str = ref('')
const isanswer = ref(false)
const activeItemIndex = ref('')
const answer_true = ref(false)
const trueValue = ref('')
const alreadySend = ref(false)
const send = ref(false)
const content = ref('')
const cate_id = ref('')
const title = ref('')
const question = ref('')
const type = ref(0)
const options_type = ref(0)
const option = ref<any[]>([])
const checked = ref('')
const value = reactive({ value: '', ischeck: false })

onMounted(() => {
  listFun()
})

function listFun() {
  const pageVal = page.value
  const sizeVal = size.value
  uni.showLoading({ title: '加载中', mask: true })

  const getIntegralListList = async () => {
    const params: AnyObject = {};
    if (state.type === "user_growth") params.type = 2;
    params.page = state.page;
    try {
      const data = (await memberApi.getCreditsLogList(
        params
      )) as unknown as CreditsLog[];
      state.loading = false;
      state.loadingType = data.length < 10 ? "noMore" : "more";
      state.integralList = [...state.integralList, ...data,];
    } catch (e) {
      state.loading = false;
    }
  };


  service({
    ...questionListApi,
    data: { page: pageVal, size: sizeVal }
  })
    .then((resp: any) => {
      uni.hideLoading()
      let concat = list.value.concat(resp.data.list)
      concat.forEach((item: any) => {
        let option_new: any = {}
        let toption = item.option
        for (let key in toption) {
          option_new[key] = { ischeck: false, value: toption[key] }
        }
        item.option = option_new
      })
      try {
        uni.setStorageSync('questionList', concat)
        uni.setStorageSync('cates', cates.value)
      } catch (e) {
        console.log('CatchClause', e)
      }
      questionList.value = concat
      cates.value = resp.data.cates
      page.value = page.value + 1
      setShuffleindex()
      if (resp.data.length != 0) {
        // wx.showToast({
        //   title: "加载第" + (page + 1) + "页成功",
        //   icon: "success"
        // });
      } else {
        uni.showToast({ title: '我是有底线的', icon: 'none' })
      }
    })
    .catch((error: any) => {
      //console.log("请求列表失败", error);
    })
}

function setShuffleindex() {
  let count = generateArray(0, questionList.value.length - 1)
  shuffleIndex.value = shuffle(count).slice(0, num.value)
  showcatebg.value = true
}

function shuffle(arr: number[]) {
  let i = arr.length
  while (i) {
    let j = Math.floor(Math.random() * i--)
    ;[arr[j], arr[i]] = [arr[i], arr[j]]
  }
  return arr
}

function radioChange(e: any) {
  chooseValue.value[index.value] = e.detail.value
}

function checkboxChange(e: any) {
  chooseValue.value[index.value] = e.detail.value.sort()
  let nowoption = questionList.value[shuffleIndex.value[index.value]].option
  for (let key1 in nowoption) {
    nowoption[key1].ischeck = my_in_array(key1, e.detail.value)
  }
  questionList.value[shuffleIndex.value[index.value]].option = nowoption
}

function my_in_array(search: any, array: any[]) {
  for (let i in array) {
    if (array[i] == search) {
      return true
    }
  }
  return false
}

function outTest() {
  uni.showModal({
    title: '提示',
    content: '你真的要退出答题吗？',
    success(res: any) {
      if (res.confirm) {
        uni.switchTab({ url: '../home/home' })
      }
    }
  })
}

function requeren() {
  isanswer.value = false
  pop_box_display.value = 'none'
}

function queren() {
  if (chooseValue.value[index.value] == undefined || chooseValue.value[index.value].length == 0) {
    uni.showToast({
      title: '请选择至少一个答案!',
      icon: 'none',
      duration: 2000
    })
    return
  }
  chooseError()
}

function nextSubmit() {
  clearInterval(setTimer)
  pop_box_display.value = 'none'
  activeItemIndex.value = ''
  if (index.value < shuffleIndex.value.length - 1) {
    isanswer.value = false
    index.value = index.value + 1
  } else {
    if (!isjump.value) {
      isjump.value = true
      let wrongListStr = JSON.stringify(wrongList.value)
      let wrongListSortStr = JSON.stringify(wrongListSort.value)
      let chooseValueStr = JSON.stringify(chooseValue.value)
      uni.navigateTo({ url: '/pages/app4/results?right=' + right.value })
      let logs = uni.getStorageSync('logs') || []
      let logsList = { date: Date.now(), testId: '', score: totalScore.value }
      logs.unshift(logsList)
      uni.setStorageSync('logs', logs)
    }
  }
}

function chooseError() {
  let trueValueVal = questionList.value[shuffleIndex.value[index.value]]['true']
  let chooseVal = chooseValue.value[index.value]
  console.log('选择了' + chooseVal + '答案是' + trueValueVal)
  let astr = chooseVal.toString()
  astr = astr.replace(/,/g, '')
  console.log('选择了' + astr + '答案是' + trueValueVal)
  if (astr != trueValueVal.toString()) {
    wrong.value++
    wrongListSort.value.push(index.value)
    wrongList.value.push(shuffleIndex.value[index.value])
    totalScore.value = totalScore.value - questionList.value[shuffleIndex.value[index.value]]['scores']
    answer_true.value = false
    isanswer.value = true
    pop_box_display.value = 'flex'
    trueValue.value = trueValueVal
    second.value = 10
    autore()
  } else {
    right.value++
    isanswer.value = true
    answer_true.value = true
    pop_box_display.value = 'flex'
    trueValue.value = trueValueVal
    second.value = 10
    if (index.value >= shuffleIndex.value.length - 1) {
      nexbutton_txt.value = '查看结果'
    }
    autonext()
  }
}

function autore() {
  clearInterval(setTimer)
  setTimer = setInterval(() => {
    second.value = second.value - 1
    if (second.value <= 0) {
      second.value = 10
      alreadySend.value = false
      send.value = true
      pop_box_display.value = 'none'
      isanswer.value = false
      clearInterval(setTimer)
    }
  }, 1000)
}

function autonext() {
  clearInterval(setTimer)
  setTimer = setInterval(() => {
    second.value = second.value - 1
    if (second.value <= 0) {
      second.value = 10
      alreadySend.value = false
      send.value = true
      clearInterval(setTimer)
      nextSubmit()
    }
  }, 1000)
}

function generateArray(start: number, end: number) {
  return Array.from(new Array(end + 1).keys()).slice(start)
}

function changestyle(e: any, _dataset?: any) {
  activeItemIndex.value = e.target.dataset.index
}
</script>
<style>
page {
    height: 100%;
}
.container {
    width: 100%;
    height: 100%;
    padding: 70rpx 30rpx 50px;
    box-sizing: border-box;
    position: relative;
}

.top-txt {
    display: none;
}

.bg-pic {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}
.bg-pic > image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    position: relative;
    z-index: 5;
}
.bg-pic > image.cover {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 8;
}

.header {
    position: relative;
    z-index: 10;
    width: 100%;
}
.header image {
    width: 485rpx;
    height: 68rpx;
}

.faq {
    position: relative;
    z-index: 10;
    margin-top: 50rpx;
}

.faq-num {
    margin-bottom: 10rpx;
    color: #d01b14;
    font-size: 50rpx;
    font-weight: bold;
}

.line {
    width: 100%;
}
.line > image {
    width: 100%;
    height: 1px;
    display: block;
}

.faq .tit {
    background: #d40009;
    padding: 20rpx 20rpx;
    font-size: 36rpx;
    color: #fff;
    letter-spacing: 2px;
    line-height: 1.5;
    text-shadow: 0 9px 9px rgba(0, 0, 0, 0.36);
    box-shadow: 0 0 10px 3px rgba(63, 62, 62, 0.2);
    margin: 15rpx 0;
    max-height: 25vh;
    overflow-y: auto;
}

.faq-box {
    padding: 10rpx;
}
.faq-box .item {
    padding: 5rpx 20rpx;
    font-size: 34rpx;
    color: #d21b12;
    margin-top: 10px;
    cursor: pointer;
    position: relative;
}
.faq-box .item radio,
.faq-box .item checkbox {
    display: none;
}
.faq-box .active,
.faq-box .ischeck {
    color: #000;
}
.faq-box .hafe {
    margin: 10rpx;
    width: 40%;
}
.faq-box .hafe .view {
    padding: 10rpx;
}
.faq-box .active .view {
    border: 1px solid #d40009;
}
.faq-box .ischeck .view {
    border: 1px solid #d40009;
}

.faq-box .item .state {
    position: absolute;
    right: 10rpx;
    top: calc(50% - 18rpx);
}
.faq-box .item .state image {
    width: 36rpx;
    height: 36rpx;
}

.faq-btn {
    position: absolute;
    bottom: 160rpx;
    left: 0;
    right: 0;
    z-index: 10;
    width: 100%;
    text-align: center;
    box-sizing: border-box;
}

.faq-btn .btn {
    width: 240rpx;
    background: #bd150d;
    border-radius: 45rpx;
    padding: 15rpx 0;
    font-size: 34rpx;
    color: #fff;
    letter-spacing: 2px;
    text-shadow: 0 9px 9px rgba(0, 0, 0, 0.36);
    box-shadow: 5px 2px 15px rgba(0, 0, 0, 0.2) inset;
    overflow: inherit;
    margin: 0;
    display: inline-block;
}
.faq-btn button[disabled='true'] {
    background: #bd150d !important;
}
.btn-box {
    display: flex;
    -webkit-justify-content: center;
    align-items: center;
    padding: 0 50rpx;
}

.btn-box .btn {
    position: relative;
}
.btn-box .btn image {
    width: 40rpx;
    height: 40rpx;
    position: absolute;
    left: -50rpx;
    top: 20rpx;
}
.btn-box .btn:last-child {
    margin-left: 20rpx;
}

.pop-box {
    position: absolute;
    z-index: 20;
    top: 145rpx;
    bottom: 255rpx;
    left: 30rpx;
    right: 30rpx;
    padding: 30rpx;
    box-sizing: border-box;
    background: rgba(0, 0, 0, 0.66);
    display: flex;
    flex-wrap: wrap;
    align-content: center;
}
.pop-box text {
    font-size: 50rpx;
    font-weight: bold;
    color: #fff;
    border-bottom: 1px solid #f1db91;
    padding: 0 0 20rpx 0;
    width: 100%;
}

.faq-tips {
    margin-top: 20rpx;
    font-size: 30rpx;
    color: #fff;
    line-height: 24px;
}

/* pages/test/test.wxss */
.page {
    padding: 20rpx;
}
.page__bd {
    padding: 20rpx;
}
.my-choosebox {
    display: block;
    margin-bottom: 20rpx;
}
.toindex-btn {
    margin-top: 20rpx;
    display: inline-block;
    line-height: 2.3;
    font-size: 13px;
    padding: 0 1.34em;
    color: #576b95;
    text-decoration: underline;
    float: right;
}
</style>
